package com.winchain.chainbill.bill.biz.discount.cmd;

import com.shell.bee.acct.transaction.po.AcctTxRec;
import com.shell.framework.command.CallbackContext;
import com.shell.framework.command.CommandContext;
import com.shell.framework.command.ICallback;
import com.shell.framework.command.ICommand;
import com.winchain.chainbill.bill.base.po.CbDct;
import com.winchain.chainbill.bill.base.po.CbRec;
import com.winchain.chainbill.bill.base.po.CbStats;
import com.winchain.chainbill.bill.base.service.CbStatsService;
import com.winchain.chainbill.bill.biz.Bill;
import java.math.BigDecimal;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class BillDctStatsCmd implements ICommand<Bill<CbDct>>, ICallback<Bill<CbDct>, AcctTxRec> {
	@Autowired
	private CbStatsService cbStatsService;

	public boolean execute(CommandContext<Bill<CbDct>> context) throws Exception {
		return false;
	}

	public boolean callback(CallbackContext<Bill<CbDct>, AcctTxRec> context) throws Exception {
		CbRec record = ((Bill) context.getSource()).getRec();
		CbStats stats = (CbStats) this.cbStatsService.selectByKey(record.getRootId());
		int chdNum = stats.getChdNum().intValue();
		BigDecimal dctAmt = stats.getDctAmt();
		if (dctAmt == null) {
			dctAmt = new BigDecimal("0");
		}
		CbDct cbDct = (CbDct) ((Bill) context.getSource()).getSource();

		List<Bill<CbDct>> children = (List) context.getValue("children");
		if ((children != null) && (children.size() > 0)) {
			chdNum += children.size();
			for (Bill<CbDct> bill : children) {
				if (((CbDct) bill.getSource()).getDctAmt() != null) {
					dctAmt = dctAmt.add(((CbDct) bill.getSource()).getDctAmt());
				}
			}
		} else {
			dctAmt = dctAmt.add(cbDct.getDctAmt());
		}
		stats.setChdNum(Integer.valueOf(chdNum));
		stats.setDctAmt(dctAmt);
		if (stats != null) {
			this.cbStatsService.updateAll(stats);
		}
		return false;
	}
}
